package ip.controller;
/***********************************************************************
 * Module:  CreateCategoryController.java
 * Author:  mojsilo
 * Purpose: Defines the Class CreateCategoryController
 ***********************************************************************/

import ip.command.CreateCategoryCommand;
import ip.dto.CategoryDTO;
import ip.dto.UserDTO;
import ip.exceptions.ApplicationException;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

/**
 * @web.servlet
 * 	name="CreateCategoryController"
 * @web.servlet-mapping
 * 	url-pattern="/control/CreateCategory"
 */
public class CreateCategoryController extends HttpServlet
{
	private static final long serialVersionUID = -112502441977331112L;
	private Logger logger = Logger.getLogger(this.getClass());
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try{
			logger.info("doGet(...)");
			HttpSession session = request.getSession(true);      
			UserDTO adminDto = (UserDTO) session.getAttribute("administrator");
			CategoryDTO categoryDTO = null;

			if(adminDto == null){
				response.sendRedirect(response.encodeRedirectURL("../jsp/login_administrator.jsp"));
				return;
			}
			categoryDTO = new CategoryDTO();
			categoryDTO.setName(request.getParameter("name"));
			
			logger.debug("doGet(...) - categoryDTO: "+categoryDTO);
			CreateCategoryCommand createCategoryCommand = new CreateCategoryCommand();
			createCategoryCommand.setCategoryDTO(categoryDTO);
			createCategoryCommand.init();
			createCategoryCommand.execute();
			createCategoryCommand.dispose();
			getServletConfig().getServletContext().getRequestDispatcher("/control/Categories").forward(request, response);
		}
		catch (ApplicationException e) {
			logger.error(e);
			request.setAttribute("error", e.getMessage());
			getServletConfig().getServletContext().getRequestDispatcher("error.jsp").forward(request, response);
		}
		catch (Exception e) {
			logger.error(e);
			request.setAttribute("error", "Unexpected error!!");//kako ovo bolje odraditi???
			getServletConfig().getServletContext().getRequestDispatcher("error.jsp").forward(request, response);
		}


	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		logger.info("doPost(...)");
		doGet(request, response);
	}

}